package com.a2.appa3.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.Resbuildground;
import com.a2.appa3.util.OnItemClickListener;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.WebSocketUtils2;

import org.json.JSONObject;

import java.net.URLEncoder;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;

public class GroundActivity extends BaseActivitySimple {

    @BindView(R.id.ivback)
    ImageView ivback;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    @BindView(R.id.headerButtonRoot)
    LinearLayout headerButtonRoot;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.linearlayout)
    LinearLayout linearlayout1;
    @BindView(R.id.grouplist)
    RecyclerView grouplist;
    @BindView(R.id.hideimg)
    ImageView hideimg;
    private Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
        hideimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linearlayout1.setVisibility(View.GONE);
            }
        });
        headerTitle.setText("群组列表");
        headerButton.setImageResource(R.mipmap.newgoun);
        headerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(GroundActivity.this, NewgroundActivity.class));

                finish();
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        grouplist.setLayoutManager(linearLayoutManager);
        adapter = new Adapter();
        grouplist.setAdapter(adapter);
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_ground;
    }

    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @Override
        public MViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MViewHolder(LayoutInflater.from(GroundActivity.this)
                    .inflate(R.layout.groundlist_item, parent, false));

        }


        @Override
        public void onBindViewHolder(final MViewHolder holder, final int position) {
            holder.chat_name.setText(Info.roomList.get(position).room_name);
            holder.timetext.setVisibility(View.GONE);
            Glide.with(GroundActivity.this).load(HttpAdress.getuseAdress() +
                    Info.roomList.get(position).head_img).error(R.mipmap.default_head).into(holder.chatimge);
            holder.chatcontent.setText(Info.roomList.get(position).lastMsg);
            holder.group_linear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        String str = "";
                        Intent intent = new Intent(GroundActivity.this, ChatActivity1.class);
                        SYSOUtils.sOut_("danliapdan群聊+++++++++++++++++++++++++++++++++++++++++++");
                        final JSONObject result = new JSONObject();
                        result.put("controller", "Action");
                        result.put("action", "openWindow");
                        result.put("type", "room");
                        result.put("id", Info.roomList.get(position).room_id + "");
                        SYSOUtils.sOut_("ContactsAdapter生成json为" + result.toString());
                        String text1 = URLEncoder.encode(result.toString(), "utf-8");
                        String encodeWord = null;
                        encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                        str = "type=ins&message=" + encodeWord;
                        intent.putExtra("chattype", "room");
                        SYSOUtils.sOut_("ContactsAdapter最终结果为" + str);
                        WebSocketUtils2.getInstance().sendMsg(str);
                        intent.putExtra("chatname",  Info.roomList.get(position).room_name);
                        intent.putExtra("chatid",  Info.roomList.get(position).room_id + "");
//                        SYSOUtils.sOut_("聊天室跳转之前" + list.get(position).id);
                        startActivity(intent);
                        str = null;
                    } catch (Exception e) {
                    }
                }
            });

            holder.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((SwipeMenuLayout) holder.itemView).quickClose();
                    //这里开始网络请求
                    HttpJsonUtils.getHttpApiInstance()
                            .releaseRoom(HttpAdress.getuseAdress() + "api/chatapi/ChatRoom/releaseRoom", Info.roomList.get(position).room_id + "", Info.Token)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new CustomObserver<Resbuildground>() {
                                @Override
                                protected void onCustomNext(Resbuildground resLogin) {
                                    if (resLogin.code == 0) {
//                                        Info.roomList.remove(position);
                                        adapter.notifyDataSetChanged();
                                        SYSOUtils.sOut_("CHANGDUDDDDDDDDDDDDDDDDDDDDD" + Info.roomList.size());
                                    } else {
                                        Toast.makeText(GroundActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                                    }

                                }

                                @Override
                                protected void onSubscribeCustom(Disposable disposable) {
                                }

                                @Override
                                protected void onErrorCustom(Throwable e) {

                                }
                            });
                }
            });
        }

        @Override
        public int getItemCount() {
            return Info.roomList.size();

        }

        @Override
        public void onItemClick(View view, int position) {

        }

        class MViewHolder extends RecyclerView.ViewHolder {
            TextView acceptbt, chatcontent, chat_name, timetext;
            ImageView chatimge;
            Button btnDelete;
            LinearLayout group_linear;

            MViewHolder(View itemView) {
                super(itemView);
                chatimge = (ImageView) itemView.findViewById(R.id.user_img);
                acceptbt = (TextView) itemView.findViewById(R.id.acceptbt);
                chat_name = (TextView) itemView.findViewById(R.id.chat_name);
                timetext = (TextView) itemView.findViewById(R.id.timetext);
                chatcontent = (TextView) itemView.findViewById(R.id.chatcontent);
                btnDelete = (Button) itemView.findViewById(R.id.btnDelete);
                group_linear = (LinearLayout) itemView.findViewById(R.id.group_linear);
            }
        }
    }
}
